# encoding: utf-8
require 'will_paginate/array'

class ProducesController < ApplicationController

	#There have admin and user actions

	#For Admin

		def index
			list
			render('list')
		end

		def list_coffee
			@produces = Produce.find(:all,
			 :conditions => ["type_of_produce = ?", "coffee"], :order => "add_day DESC" ).paginate(:page => params[:page], :per_page => 5)
		end

		def list_snack
			@produces = Produce.find(:all,
			 :conditions => ["type_of_produce = ?", "snack"], :order => "add_day DESC").paginate(:page => params[:page], :per_page => 5)
		end

		def list_beverage
			@produces = Produce.find(:all,
			 :conditions => ["type_of_produce = ?", "beverage"], :order => "add_day DESC").paginate(:page => params[:page], :per_page => 5)
		end

		def list
			@produces = Produce.order("produces.add_day DESC").paginate(:page => params[:page], :per_page => 5)
			#@pages = Produce.paginate(:page => params[:page], :per_page => 5)
		end

		def show
			@produce = Produce.find(params[:id])
			
		end

		def new
			@produce = Produce.new
		end

		def create
			@produce = Produce.new(params[:produce])

		  	if @produce.save
		  		redirect_to(:action => 'list')
		  	else
		  		render('new')
		  	end
		end

		#------need to alert when quantity of produces is zero---------------------------
		def add_to_cart
			@produce = Produce.find(params[:id])
			if session[:user]
      			@cart = Cart.find(:first, :conditions => ["user_id = ?", session[:user].id])
				$i = 0
				$num = @cart.cart_produces.size
				until $i == $num
					if $num == 0
						break
					end
					if @cart.cart_produces[$i].produce_id == @produce.id
						redirect_to :action => "show", :id => @produce.id
						return false
					end 		
					$i = $i + 1
				end	
				@temp = CartProduce.new(:cart_id => @cart.id, :produce_id => @produce.id, :time_new => Time.now)
				@cart.cart_produces << @temp
				redirect_to :action => "show", :id => @produce.id
				return true#need to remove time column in carts table
    		end
		    flash[:warning]='Bạn cần đăng ký hoặc đăng nhập để tiếp tục'
		    session[:return_to]=request.url
		    redirect_to :controller => "users", :action => "login"
		    return false 
		end
	#End for Admin


	#For User: Add produce to Cart

end
